#!/bin/bash

# FTP断点续传测试脚本
echo "🔄 FTP断点续传测试脚本"
echo "======================="

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 函数：打印成功消息
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

# 函数：打印错误消息
print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 函数：打印警告消息
print_warning() {
    echo -e "${YELLOW}⚠️ $1${NC}"
}

# 函数：打印信息消息
print_info() {
    echo -e "${YELLOW}ℹ️ $1${NC}"
}

# 函数：打印步骤消息
print_step() {
    echo -e "${BLUE}🔄 $1${NC}"
}

# 检查Rust是否安装
check_rust() {
    print_info "检查Rust环境..."
    if command -v cargo &> /dev/null; then
        print_success "Rust环境正常"
        cargo --version
    else
        print_error "Rust未安装，请先安装Rust"
        exit 1
    fi
}

# 构建客户端
build_client() {
    print_info "构建FTP客户端..."
    if cargo build -p ftp-client; then
        print_success "客户端构建成功"
    else
        print_error "客户端构建失败"
        exit 1
    fi
}

# 创建测试文件
create_test_files() {
    print_info "创建断点续传测试文件..."
    
    # 创建大文件用于测试断点续传
    dd if=/dev/urandom of=resume_test.bin bs=1024 count=10240 2>/dev/null  # 10MB文件
    print_success "创建断点续传测试文件: resume_test.bin (10MB)"
    
    # 创建部分文件用于模拟中断
    dd if=resume_test.bin of=partial_test.bin bs=1024 count=5120 2>/dev/null  # 5MB部分文件
    print_success "创建部分文件: partial_test.bin (5MB)"
}

# 测试上传断点续传
test_upload_resume() {
    print_step "测试上传断点续传..."
    
    # 第一次上传（模拟中断）
    print_info "第一次上传（模拟中断）..."
    timeout 5s cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --upload resume_test.bin --local_path resume_test.bin 2>&1 | head -20
    
    # 检查服务器上的部分文件
    print_info "检查服务器上的部分文件..."
    if cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --download resume_test.bin --local_path downloaded_partial.bin 2>&1 | grep -q "Download completed"; then
        print_success "部分文件下载成功"
        
        # 比较文件大小
        local_size=$(stat -c%s downloaded_partial.bin 2>/dev/null || stat -f%z downloaded_partial.bin 2>/dev/null)
        original_size=$(stat -c%s resume_test.bin 2>/dev/null || stat -f%z resume_test.bin 2>/dev/null)
        
        if [ "$local_size" -lt "$original_size" ]; then
            print_success "确认文件未完全上传，可以进行断点续传"
        else
            print_warning "文件已完全上传，无法测试断点续传"
        fi
    else
        print_warning "部分文件下载失败"
    fi
    
    # 第二次上传（断点续传）
    print_info "第二次上传（断点续传）..."
    if cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --upload resume_test.bin --local_path resume_test.bin 2>&1 | grep -q "Resumed from offset"; then
        print_success "断点续传成功！"
    else
        print_warning "断点续传失败或文件已完整"
    fi
}

# 测试下载断点续传
test_download_resume() {
    print_step "测试下载断点续传..."
    
    # 创建部分下载文件
    print_info "创建部分下载文件..."
    dd if=/dev/urandom of=partial_download.bin bs=1024 count=5120 2>/dev/null  # 5MB部分文件
    print_success "创建部分下载文件: partial_download.bin (5MB)"
    
    # 尝试断点续传下载
    print_info "尝试断点续传下载..."
    if cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --download resume_test.bin --local_path partial_download.bin 2>&1 | grep -q "Resumed from offset"; then
        print_success "下载断点续传成功！"
        
        # 验证文件完整性
        if diff resume_test.bin partial_download.bin > /dev/null; then
            print_success "文件完整性验证通过"
        else
            print_warning "文件完整性验证失败"
        fi
    else
        print_warning "下载断点续传失败"
    fi
}

# 测试禁用断点续传
test_no_resume() {
    print_step "测试禁用断点续传..."
    
    # 使用--no-resume选项
    print_info "使用--no-resume选项上传..."
    if cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --upload resume_test.bin --local_path resume_test.bin --no-resume 2>&1 | grep -q "no resume"; then
        print_success "禁用断点续传功能正常"
    else
        print_warning "禁用断点续传功能测试失败"
    fi
}

# 测试REST命令
test_rest_command() {
    print_step "测试REST命令..."
    
    # 测试设置偏移量
    print_info "测试REST命令..."
    if cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --interactive 2>&1 | head -10; then
        print_success "REST命令测试完成"
    else
        print_warning "REST命令测试失败"
    fi
}

# 测试SIZE命令
test_size_command() {
    print_step "测试SIZE命令..."
    
    # 测试获取文件大小
    print_info "测试SIZE命令..."
    if cargo run -p ftp-client -- --host 127.0.0.1 --port 21 --username testuser --password testpass --interactive 2>&1 | head -10; then
        print_success "SIZE命令测试完成"
    else
        print_warning "SIZE命令测试失败"
    fi
}

# 清理测试文件
cleanup_test_files() {
    print_info "清理断点续传测试文件..."
    rm -f resume_test.bin partial_test.bin downloaded_partial.bin partial_download.bin
    print_success "测试文件已清理"
}

# 运行完整测试
run_full_test() {
    print_info "开始FTP断点续传完整测试"
    
    check_rust
    build_client
    create_test_files
    test_upload_resume
    test_download_resume
    test_no_resume
    test_rest_command
    test_size_command
    cleanup_test_files
    
    print_success "所有断点续传测试完成！"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  build      - 构建客户端"
    echo "  upload     - 测试上传断点续传"
    echo "  download   - 测试下载断点续传"
    echo "  no-resume  - 测试禁用断点续传"
    echo "  rest       - 测试REST命令"
    echo "  size       - 测试SIZE命令"
    echo "  test       - 运行所有测试"
    echo "  cleanup    - 清理测试文件"
    echo "  help       - 显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 build      # 构建客户端"
    echo "  $0 test       # 运行所有测试"
    echo "  $0 upload     # 只测试上传断点续传"
}

# 主函数
main() {
    case "${1:-test}" in
        "build")
            check_rust
            build_client
            ;;
        "upload")
            check_rust
            test_upload_resume
            ;;
        "download")
            check_rust
            test_download_resume
            ;;
        "no-resume")
            check_rust
            test_no_resume
            ;;
        "rest")
            check_rust
            test_rest_command
            ;;
        "size")
            check_rust
            test_size_command
            ;;
        "test")
            run_full_test
            ;;
        "cleanup")
            cleanup_test_files
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            print_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"
